package cn.thornbird.orgsync.service.impl;

import cn.thornbird.orgsync.entity.User;
import cn.thornbird.orgsync.model.UserData;
import cn.thornbird.orgsync.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findFirstByUsernameIgnoreCase(username);
        if (user == null) {
            user = userRepository.findFirstByMobile(username);
        }
        if (user == null) {
            user = userRepository.findFirstByEmailIgnoreCase(username);
        }
        if (user == null) {
            throw new UsernameNotFoundException("username not found");
        }
        return new UserData(user, null);
    }

}
